<?php

namespace App\Http\Controllers;

use App\Events\OrderCompletedEvent;
use App\Exports\OrdersExport;
use App\Exports\UsersExport;
use App\Models\ClickLog;
use App\Models\Config;
use App\Models\DistributorUser;
use App\Models\OrderInfo;
use App\Models\ProxyUser;
use App\Models\StaticProxyDetail;
use App\Models\StaticRegion;
use App\Models\StatisticDetail;
use App\Models\TrafficDetail;
use App\Models\User;
use App\Services\OrderService;
use App\Services\ProxyService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class ManageController extends Controller
{
    protected $orderService;

    public function __construct(OrderService  $orderService)
    {
        $this->orderService = $orderService;
    }

    public function userList(Request $request)
    {
        $user_id = $request->input('user_id');
        $username = $request->input('username');
        $is_buy = $request->input('is_buy');
        $distributor = $request->input('distributor');
        $is_export = $request->input('is_export', 0);
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;

        $goods = config('goods.dynamic.zh-cn');

        $query = User::where('status', '!=', 0);
        if (!empty($user_id)) {
            $query->where('id', $user_id);
        }
        if (!empty($username)) {
            $query->where(function ($query) use ($username) {
                $query->where('username', 'like', '%' . $username . '%')->orWhere('email', 'like', '%' . $username . '%');
            });
        }
        if (is_numeric($is_buy) && in_array($is_buy, [1, 2])) {
            if ($is_buy == 1) {
                $query->where('has_dynamic', 1);
            } else {
                $query->where('has_static', 1);
            }
        }
        if (!empty($distributor)) {
            $distributor_user_id = DistributorUser::where('invite_code', $distributor)->value('user_id');
            $query->where('invite_userid', $distributor_user_id);
        }
        if ($is_export == 1) {
            $start_time = date('Y-m-d', strtotime('-1 months'));
            $query->where('created_at', '>=', $start_time);
            $list = $query->orderBy('id', 'desc')->get();
            $data = [];
            foreach ($list as $item) {
                $invite_username = '';
                if (!empty($item->invite_userid)) {
                    $invite_username = User::where('id', $item->invite_userid)->value('email');
                }
                $proxy_status = ProxyUser::where('user_id', $item->id)->value('status');
                $data[] = [
                    $item->created_at->format('Y-m-d'),
                    $item->email,
                    $item->username,
                    $invite_username,
                    $proxy_status == 1 ? '是' : '',
                    $item->amount,
                ];
            }
            $headings = ['注册时间', '邮箱', '内部帐号', '分销名称', '是否激活', '累计金额'];
            return Excel::download(new UsersExport($data, $headings), 'users_export.xlsx');
        }

        $count = $query->count();
        $list = $query->offset($offset)->limit($limit)->orderBy('created_at', 'desc')->get();
        foreach ($list as $item) {
            $order_amount = OrderInfo::where('user_id', $item->id)->where('status', 1)->sum('amount');
            $item->order_amount = $order_amount;
            $goods_id = OrderInfo::where('user_id', $item->id)->where('status', 1)->orderBy('updated_at', 'desc')->value('goods_id');
            if (!empty($goods_id)) {
                $item->goods_info = $goods[$goods_id]['title'] ?? '';
            } else {
                $item->goods_info = '';
            }
            $item->invite_username = '';
            if (!empty($item->invite_userid)) {
                $item->invite_code = DistributorUser::where('user_id', $item->invite_userid)->value('invite_code');
                $item->invite_username = User::where('id', $item->invite_userid)->value('email');
            }
            $proxy_status = ProxyUser::where('user_id', $item->id)->value('status');
            $item->proxy_status = $proxy_status ?? 0;

            $current_time = date('Y-m-d H:i:s');
            $select = "COUNT(*) AS total_cnt, SUM(CASE WHEN expired_time > '" . $current_time . "' OR expired_time IS NULL THEN 1 ELSE 0 END) AS unexpired_cnt, SUM(CASE WHEN expired_time <  '" . $current_time . "' THEN 1 ELSE 0 END) AS expired_cnt";
            $staticCnt = StaticProxyDetail::selectRaw($select)->where('user_id', $item->id)->first();
            $static_data = [
                'total_cnt' => $staticCnt->total_cnt ?? 0,
                'unexpired_cnt' => $staticCnt->unexpired_cnt ?? 0,
                'expired_cnt' => $staticCnt->expired_cnt ?? 0,
            ];
            $item->static_data = $static_data;
        }
        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }

    public function userInfo(Request $request)
    {
        $user_id = $request->input('user_id');
        $limit = 10;
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;

        if (empty($user_id)) {
            return response()->json([
                'errcode' => 0,
                'errmsg' => '操作成功',
                'data' => [
                    'count' => 0,
                    'list' => []
                ]
            ]);
        }

        $user = User::find($user_id);
        if (empty($user)) {
            return response()->json([
                'errcode' => 0,
                'errmsg' => '操作成功',
                'data' => [
                    'count' => 0,
                    'list' => []
                ]
            ]);
        }

        $query = TrafficDetail::where('user_id', $user_id);
        $count = $query->count();
        $list = $query->offset($offset)->limit($limit)->orderBy('create_day', 'desc')->get();
        foreach ($list as $item) {
            $item->total = bcadd($item->download_flow, $item->upload_flow, 2);
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list,
                'user' => $user
            ]
        ]);
    }

    public function resetPass(Request $request)
    {
        $user_id = $request->input('user_id');
        $rules = [
            'user_id' => 'required|exists:users,id'
        ];

        $messages = [
            'user_id.required' => '缺少用户信息',
            'user_id.exists' => '用户不存在'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'errcode' => -1,
                'errmsg' => $errors->first(),
            ]);
        }

        $user = User::find($user_id);
        $user->password = Hash::make('IPXPROXYCOM');
        $user->save();

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function recharge(Request $request)
    {
        $rules = [
            'user_id' => 'required|exists:users,id',
            'proxy_type' => 'required',
            'goods_info' => 'required',
            'quantity' => 'required|numeric',
            'amount' => 'required',
            'pay_way' => 'required',
        ];

        $messages = [
            'user_id.required' => '缺少用户信息',
            'user_id.exists' => '用户不存在',
            'proxy_type.required' => '请选择套餐类型',
            'goods_info.required' => '请输入套餐',
            'quantity.required' => '请输入充值数量',
            'quantity.integer' => '充值数量输入错误',
            'amount.required' => '请输入充值金额',
            'pay_way.required' => '请选择支付方式'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'errcode' => -1,
                'errmsg' => $errors->first(),
            ]);
        }

        $remark = $request->input('remark', '');
        DB::beginTransaction();
        try {
            $order_data = [
                'user_id' => $request->user_id,
                'goods_info' => $request->goods_info,
                'order_nu' => 'IPX' . date('YmdHis') . rand(100000, 999999),
                'amount' => $request->amount,
                'quantity' => $request->quantity,
                'pay_way' => $request->pay_way,
                'proxy_type' => $request->proxy_type,
                'remark' => $remark ?? '',
                'source' => 1,
                'status' => 1,
                'is_verify' => 1,
                'create_day' => date('Y-m-d')
            ];
            $orderInfo = OrderInfo::create($order_data);
            if (empty($orderInfo)) {
                throw new \Exception('创建订单失败');
            }

            // 只充流量
            $proxyService = new ProxyService();
            $result = $proxyService->rechargeTraffic($orderInfo->user_id, $orderInfo->order_nu, $orderInfo->quantity);
            if ($result['code'] !== 0) {
                throw new \Exception('充值流量失败：' . $result['msg']);
            }

            // 订单完成事件
            event(new OrderCompletedEvent($orderInfo));

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('recharge exception ' . $e->getMessage());

            return response()->json([
                'errcode' => -1,
                'errmsg' => $e->getMessage()
            ]);
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function staticRecharge(Request $request)
    {
        $rules = [
            'user_id' => 'required|exists:users,id',
            'proxy_type' => 'required',
            'country_code' => 'required',
            'line_type' => 'required',
            'business' => 'required',
            'days' => 'required',
            'quantity' => 'required|numeric',
            'amount' => 'required',
            'pay_way' => 'required',
        ];

        $messages = [
            'user_id.required' => '缺少用户信息',
            'user_id.exists' => '用户不存在',
            'proxy_type.required' => '请选择代理类型',
            'country_code.required' => '请选择国家/地区',
            'line_type.required' => '请选择IP类型',
            'business.required' => '请选择业务用途',
            'days.required' => '请选择套餐',
            'quantity.integer' => '请输入购买数量',
            'amount.required' => '请输入支付金额',
            'pay_way.required' => '请选择支付方式'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'errcode' => -1,
                'errmsg' => $errors->first(),
            ]);
        }

        if (App::getLocale() == 'en') {
            $static_region = Cache::remember('static_region_en', 86400, function () {
                return StaticRegion::pluck('name', 'code')->toArray();
            });
        } else {
            $static_region = Cache::remember('static_region_zh', 86400, function () {
                return StaticRegion::pluck('alias', 'code')->toArray();
            });
        }
        if (App::getLocale() == 'en') {
            $line_types = [
                '1' => 'basics',
                '2' => 'standard',
                '3' => 'advanced'
            ];
        } else {
            $line_types = [
                '1' => '基础',
                '2' => '标准',
                '3' => '高端'
            ];
        }

        $country_code = $request->input('country_code');
        $line_type = $request->input('line_type');
        $business = $request->input('business');
        $days = $request->input('days');
        $quantity = $request->input('quantity');
        $remark = $request->input('remark', '');

        $goods_id = 2001;
        $order_nu = 'IPX' . date('YmdHis') . rand(100000, 999999);
        $desc = $static_region[$country_code] . '-' . $line_types[$line_type] . '-' . $business . '-' . $days . '%s-' . $quantity . 'IP';
        $desc = App::getLocale() == 'en' ? sprintf($desc, 'day') : sprintf($desc, '天');

        DB::beginTransaction();
        try {
            $order_data = [
                'user_id' => $request->user_id,
                'goods_id' => $goods_id,
                'goods_info' => $desc,
                'order_nu' => $order_nu,
                'amount' => $request->amount,
                'quantity' => $request->quantity,
                'pay_way' => $request->pay_way,
                'proxy_type' => 2,
                'extend' => json_encode([
                    'country_code' => $country_code,
                    'line_type' => $line_type,
                    'business' => $business,
                    'days' => $days,
                    'quantity' => $quantity
                ]),
                'remark' => $remark ?? '',
                'source' => 1,
                'status' => 1,
                'is_verify' => 1,
                'create_day' => date('Y-m-d')
            ];
            $orderInfo = OrderInfo::create($order_data);
            if (empty($orderInfo)) {
                throw new \Exception('创建订单失败');
            }

            // 只充流量
            $proxyService = new ProxyService();
            $result = $proxyService->createStaticOrder($orderInfo->user_id, $orderInfo->order_nu);
            if ($result['code'] !== 0) {
                throw new \Exception('充值静态代理失败：' . $result['msg']);
            }

            // 订单完成事件
            event(new OrderCompletedEvent($orderInfo));

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('recharge exception ' . $e->getMessage());

            return response()->json([
                'errcode' => -1,
                'errmsg' => $e->getMessage()
            ]);
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function staticRenewRecharge(Request $request)
    {
        $rules = [
            'user_id' => 'required|exists:users,id',
            'order_nu' => 'required|exists:order_infos,order_nu',
            'days' => 'required',
            'amount' => 'required',
            'pay_way' => 'required',
        ];

        $messages = [
            'user_id.required' => '缺少用户信息',
            'user_id.exists' => '用户不存在',
            'order_nu.required' => '请提供订单号',
            'order_nu.exists' => '订单号不存在',
            'days.required' => '请选择套餐',
            'amount.required' => '请输入支付金额',
            'pay_way.required' => '请选择支付方式'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'errcode' => -1,
                'errmsg' => $errors->first(),
            ]);
        }

        if (App::getLocale() == 'en') {
            $static_region = Cache::remember('static_region_en', 86400, function () {
                return StaticRegion::pluck('name', 'code')->toArray();
            });
        } else {
            $static_region = Cache::remember('static_region_zh', 86400, function () {
                return StaticRegion::pluck('alias', 'code')->toArray();
            });
        }
        if (App::getLocale() == 'en') {
            $line_types = [
                '1' => 'basics',
                '2' => 'standard',
                '3' => 'advanced'
            ];
        } else {
            $line_types = [
                '1' => '基础',
                '2' => '标准',
                '3' => '高端'
            ];
        }

        $order_nu = $request->input('order_nu');
        $renew_days = $request->input('days');
        $amount = $request->input('amount');
        $pay_way = $request->input('pay_way');

        $source_order_info = OrderInfo::where('order_nu', $order_nu)->first();
        $extend = json_decode($source_order_info->extend, true);
        $country_code = $extend['country_code'];
        $line_type = $extend['line_type'];
        $business = $extend['business'];
        $quantity = $extend['quantity'];

        $goods_id = 2001;
        $new_order_nu = 'IPX' . date('YmdHis') . rand(100000, 999999);
        $desc = $static_region[$country_code] . '-' . $line_types[$line_type] . '-' . $business . '-' . $renew_days . '%s-' . $quantity . 'IP';
        $desc = App::getLocale() == 'en' ? sprintf($desc, 'day') : sprintf($desc, '天');

        DB::beginTransaction();
        try {
            $order_data = [
                'user_id' => $request->user_id,
                'goods_id' => $goods_id,
                'goods_info' => $desc,
                'order_nu' => $new_order_nu,
                'amount' => $amount,
                'quantity' => $quantity,
                'pay_way' => $pay_way,
                'proxy_type' => 2,
                'extend' => json_encode([
                    'country_code' => $country_code,
                    'line_type' => $line_type,
                    'business' => $business,
                    'days' => $renew_days,
                    'quantity' => $quantity,
                    'main_order_nu' => $source_order_info->order_nu,
                ]),
                'is_renew' => 1,
                'remark' => $remark ?? '',
                'source' => 1,
                'status' => 1,
                'is_verify' => 1,
                'create_day' => date('Y-m-d')
            ];
            $newOrderInfo = OrderInfo::create($order_data);
            if (empty($newOrderInfo)) {
                throw new \Exception('创建订单失败');
            }

            // 只充流量
            $proxyService = new ProxyService();
            $result = $proxyService->createStaticOrder($newOrderInfo->user_id, $newOrderInfo->order_nu);
            if ($result['code'] !== 0) {
                throw new \Exception('充值流量失败：' . $result['msg']);
            }

            // 订单完成事件
            event(new OrderCompletedEvent($newOrderInfo));

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('recharge exception ' . $e->getMessage());

            return response()->json([
                'errcode' => -1,
                'errmsg' => $e->getMessage()
            ]);
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function orderList(Request $request)
    {
        $user_id = $request->input('user_id');
        $order_nu = $request->input('order_nu');
        $username = $request->input('username');
        $status = $request->input('status');
        $is_export = $request->input('is_export', 0);
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;

        $query = OrderInfo::query();
        if (!empty($user_id)) {
            $query->where('user_id', $user_id);
        }
        if (!empty($order_nu)) {
            $query->where('order_nu', $order_nu);
        }
        if (!empty($username)) {
            $user_id = User::where('username', $username)->value('id');
            if (!empty($user_id)) {
                $query->where('user_id', $user_id);
            }
        }
        if (is_numeric($status) && in_array($status, [0, 1, 2])) {
            if ($status == 1) {
                $query->where('status', 1)->where('is_verify', 1);
            } elseif ($status == 2) {
                $query->where('status', 1)->where('is_verify', 1)->where('source', 1);
            } else {
                $query->where('status', 0);
            }
        }
        if ($is_export == 1) {
            $start_time = date('Y-m-d', strtotime('-2 months'));
            $query->where('create_day', '>=', $start_time)->where('status', 1)->where('is_verify', 1);
            $list = $query->orderBy('id', 'desc')->get();
            $data = [];
            foreach ($list as $item) {
                $username = User::where('id', $item->user_id)->value('email');
                if ($item->pay_way == 'usdt') {
                    $pay_way_str = 'USDT';
                } elseif ($item->pay_way == 'alipay') {
                    $pay_way_str = '支付宝';
                } elseif ($item->pay_way == 'card') {
                    $pay_way_str = '信用卡';
                } else {
                    $pay_way_str = '其他';
                }
                $proxy_status = ProxyUser::where('user_id', $item->user_id)->value('status');
                $data[] = [
                    $item->created_at,
                    $item->order_nu,
                    $item->user_id,
                    $username,
                    $item->proxy_type == 1 ? '动态代理' : '静态代理',
                    $proxy_status == 1 ? '正常' : '未激活',
                    $item->goods_info,
                    $pay_way_str,
                    $item->amount
                ];
            }
            $headings = ['创建时间', '订单号', '用户ID', '用户名称', '代理类型', '是否激活', '套餐', '支付方式', '支付金额'];
            return Excel::download(new OrdersExport($data, $headings), 'orders_export.xlsx');
        }

        $count = $query->count();
        $list = $query->offset($offset)->limit($limit)->orderBy('created_at', 'desc')->get();
        foreach ($list as $item) {
            $item->username = $item->user->username;
            unset($item->user);
            if ($item->pay_way == 'usdt') {
                $item->pay_way_str = 'USDT';
            } elseif ($item->pay_way == 'alipay') {
                $item->pay_way_str = '支付宝';
            } elseif ($item->pay_way == 'card') {
                $item->pay_way_str = '信用卡';
            } else {
                $item->pay_way_str = '其他';
            }
            $item->pay_info = $item->pay_way_str . '/$' . $item->amount;
            $item->pay_status = '';
            if ($item->status == 0) {
                $item->pay_status = '未支付（待核对）';
            } elseif ($item->status == 1 && $item->is_verify == 1 && $item->source == 0) {
                $item->pay_status = '已支付（已核对）';
            } elseif ($item->status == 1 && $item->is_verify == 1 && $item->source == 1) {
                $item->pay_status = '已支付（手工下单）';
            }
        }
        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }

    public function orderVerify(Request $request)
    {
        $rules = [
            'user_id' => 'required|exists:users,id',
            'order_nu' => 'required|exists:order_infos',
            'remark' => 'required'
        ];

        $messages = [
            'user_id.required' => '缺少用户信息',
            'user_id.exists' => '用户不存在',
            'order_nu.required' => '缺少订单号',
            'order_nu.exists' => '订单不存在',
            'remark.required' => '必须输入备注'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'errcode' => -1,
                'errmsg' => $errors->first()
            ]);
        }

        $remark = $request->input('remark', '');
        $orderInfo = OrderInfo::where('user_id', $request->user_id)->where('order_nu', $request->order_nu)->first();
        if (empty($orderInfo)) {
            return response()->json([
                'errcode' => -1,
                'errmsg' => '订单不存在',
            ]);
        }

        DB::beginTransaction();
        try {
            $orderInfo->is_verify = 1;
            $orderInfo->status = 1;
            $orderInfo->remark = $remark;
            $orderInfo->save();

            // 只充流量
            if ($orderInfo->proxy_type == 1) {
                $proxyService = new ProxyService();
                $result = $proxyService->rechargeTraffic($orderInfo->user_id, $orderInfo->order_nu, $orderInfo->quantity);
                if ($result['code'] !== 0) {
                    throw new \Exception('充值流量失败：' . $result['msg']);
                }
            } else {
                $proxyService = new ProxyService();
                $result = $proxyService->createStaticOrder($orderInfo->user_id, $orderInfo->order_nu);
                if ($result['code'] !== 0) {
                    throw new \Exception('静态购买失败：' . $result['msg']);
                }
            }

            // 增加累计消费额
            User::where('id', $orderInfo->user_id)->increment('amount', $orderInfo->amount);

            // 订单完成事件
            event(new OrderCompletedEvent($orderInfo));

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            $orderInfo->failure = $e->getMessage();
            $orderInfo->save();

            return response()->json([
                'errcode' => 0,
                'errmsg' => $e->getMessage()
            ]);
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function payConfig()
    {
        $data = Config::first();
        $data->alipay_switch = $data->alipay_switch == 1 ? true : false;
        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => $data
        ]);
    }

    public function savePayConfig(Request $request)
    {
        $rules = [
            'usdt_address' => 'required',
            'usdt_qrcode' => 'required',
            'exchange_rate' => 'required',
            'alipay_qrcode' => 'required'
        ];

        $messages = [
            'usdt_address.required' => '缺少USDT收款地址',
            'usdt_qrcode.required' => '请上传USDT二维码',
            'exchange_rate.required' => '缺少美元汇率值',
            'alipay_qrcode.required' => '请上传支付宝二维码'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'errcode' => -1,
                'errmsg' => $errors->first(),
            ]);
        }

        Config::updateOrCreate(
            [
                'id' => 1
            ],
            [
                'usdt_address' => $request->usdt_address,
                'usdt_qrcode' => $request->usdt_qrcode,
                'exchange_rate' => $request->exchange_rate,
                'alipay_qrcode' => $request->alipay_qrcode,
                'alipay_switch' => $request->alipay_switch
            ]
        );

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function upload(Request $request)
    {
        // 验证请求
        $validator = Validator::make($request->all(), [
            'file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // 2MB限制
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errcode' => -1,
                'errmsg' => $validator->errors()
            ]);
        }

        // 处理上传
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $path = $file->storeAs('images', $fileName, 'public');

            return response()->json([
                'errcode' => 0,
                'errmsg' => '上传成功',
                'url' => Storage::url($path)
            ]);
        }

        return response()->json([
            'errcode' => -1,
            'errmsg' => '未找到上传文件'
        ]);
    }

    public function logs(Request $request)
    {
        $username = $request->input('username');
        $create_day = $request->input('create_day');
        $event_type = $request->input('event_type');
        $is_pay = $request->input('is_pay');
        $is_export = $request->input('is_export', 0);
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;

        $goods_list = config('goods.dynamic.zh-cn');

        $field = ['id', 'user_id', 'ip', 'event_type', 'is_mobile', 'goods_id', 'pay_way', 'is_pay', 'created_at'];
        $query = ClickLog::query();
        $query->select($field);
        if ($username) {
            $user_ids = User::where('username', 'like', '%' . $username . '%')->pluck('id');
            $query->whereIn('user_id', $user_ids);
        }
        if ($create_day) {
            $query->where('create_day', $create_day);
        }
        if ($event_type) {
            $query->where('event_type', $event_type);
        }
        if ($is_pay) {
            $query->where('is_pay', $is_pay);
        }
        $count = $query->count();
        $list = $query->offset($offset)->limit($limit)->orderBy('created_at', 'desc')->get();
        foreach ($list as $item) {
            $event_type = '';
            switch ($item->event_type) {
                case 'order':
                    $event_type = '点击支付';
                    break;
                case 'select_goods':
                    $event_type = '点击套餐';
                    break;
                case 'login':
                    $event_type = '登录';
                    break;
            }
            $item->goods_info = '';
            if (in_array($item->event_type, ['select_goods', 'order'])) {
                $item->goods_info = $goods_list[$item->goods_id]['title'] ?? '';
            }
            if ($item->event_type == 'order') {
                $exist = OrderInfo::where('order_nu', $item->order_nu)->where('status', 1)->exists();
                $is_pay = $exist ? 1 : 0;
                $item->is_pay = $is_pay;
                ClickLog::where('id', $item->id)->update(['is_pay' => $is_pay]);
            }
            $item->event_type = $event_type;
            if ($item->pay_way == 'usdt') {
                $item->pay_way_str = 'USDT';
            } elseif ($item->pay_way == 'alipay') {
                $item->pay_way_str = '支付宝';
            } elseif ($item->pay_way == 'card') {
                $item->pay_way_str = '信用卡';
            } else {
                $item->pay_way_str = '';
            }
            $username = User::where('id', $item->user_id)->value('email');
            $item->username = $username;
            $item->device = $item->is_mobile ? '移动端' : 'PC端';
            $item->create_time = date_format($item->created_at, 'Y-m-d H:i:s');

        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }

    public function statistics(Request $request)
    {
        $list = StatisticDetail::select(DB::raw('
    create_day,
    MAX(CASE WHEN type = "login" THEN count ELSE 0 END) as login_count,
    MAX(CASE WHEN type = "select_goods" THEN count ELSE 0 END) as goods_count,
    MAX(CASE WHEN type = "order" THEN count ELSE 0 END) as order_count,
    SUM(CASE WHEN type = "order" AND is_pay = 1 THEN 1 ELSE 0 END) as pay_count,
    SUM(CASE WHEN type = "order" AND is_pay = 1 THEN amount ELSE 0 END) as amount
'))
            ->from(DB::raw('(
    SELECT
        create_day,
        type,
        is_pay,
        COUNT(*) as count,
        SUM(CASE WHEN type = "order" AND is_pay = 1 THEN amount ELSE 0 END) as amount
    FROM
        statistic_details
    WHERE
        create_day >= CURDATE() - INTERVAL 9 DAY
    GROUP BY
        create_day,
        type,
        is_pay
) as subquery'))
            ->groupBy('create_day')
            ->orderBy('create_day', 'desc')
            ->get();

        $count = 1;
        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }
}
